#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mw_list.h"

typedef unsigned char u_int8_t;
typedef unsigned short u_int16_t;

#define IEEE80211_ADDR_LEN	(6*3)
#define MAX_KEY_LEN			32

struct dcwep_key
{
	struct list_head list;
	u_int8_t bssid[IEEE80211_ADDR_LEN];
	u_int16_t wk_keylen;
	u_int8_t  wk_key[MAX_KEY_LEN];
};


/* 维护一个BSSID-KEY表 */
static DEFINE_LIST_HEAD(wepkey_list) = LIST_HEAD_INIT(wepkey_list);
#define for_each_key(x) \
	list_for_each_entry(x,&wepkey_list,list)

void dcclear_wep_key(void)
{
    struct dcwep_key* item;
    struct dcwep_key* tmp;

    list_for_each_entry_safe(item, tmp, &wepkey_list, list) {
        list_del(&item->list);
        free(item);
    }
    
    return;
}

void dcprint_wep_key(int step)
{
    struct dcwep_key* item;
   	for_each_key(item){
        printf("step:%d bssid:%s, len:%d, key:%s\n", step, item->bssid, item->wk_keylen, item->wk_key);
    }
}

struct dcwep_key *dcfind_wep_key(u_int8_t *bssid)
{
    struct dcwep_key* item = NULL;
    
    for_each_key(item){
        if (!memcmp(bssid, item->bssid, IEEE80211_ADDR_LEN)) {
            return item;
        }
    }

    return NULL;
}

int dcadd_wep_key(u_int8_t *bssid, u_int8_t *key, u_int16_t keylen)
{
    struct dcwep_key* item = NULL;
    
    if ((NULL == bssid) || (keylen >= MAX_KEY_LEN)) {
        return -1;
    }

    /* find it */
    item = dcfind_wep_key(bssid);
    if (NULL == item) {
        item=(struct dcwep_key*)malloc(sizeof(struct dcwep_key));
        memset(item, 0x0, sizeof(struct dcwep_key));
        memcpy(item->bssid, bssid, IEEE80211_ADDR_LEN);
        item->wk_keylen = keylen;
        memcpy(item->wk_key, key, keylen);
        
        INIT_LIST_HEAD(&item->list);
        list_add_tail(&item->list,&wepkey_list);
    }
    else {
        /* exist ,so modify it */
        item->wk_keylen = keylen;
        memset(item->wk_key, 0x0, MAX_KEY_LEN);
        memcpy(item->wk_key, key, keylen);
    }
    
    return 0;
}



int main (int argc, const char *argv[])
{
	dcprint_wep_key(1);
	dcadd_wep_key("00:01:02:03:04:00", "11111", 5);
	dcadd_wep_key("00:01:02:03:04:01", "22222", 5);
	dcadd_wep_key("00:01:02:03:04:02", "33333", 5);
	dcadd_wep_key("00:01:02:03:04:03", "44444", 5);
	dcclear_wep_key();
	dcadd_wep_key("00:01:02:03:04:04", "55555", 5);
	dcadd_wep_key("00:01:02:03:04:05", "66666", 5);
	dcadd_wep_key("00:01:02:03:04:01", "77777", 5);
	dcprint_wep_key(2);


	return 0;
}
